import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.concurrent.TimeUnit;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;


public class KDF1 {

	WebDriver myFD = new FirefoxDriver();
	String[][] xTC, xTS;
	int xRows, xCols;
	String[][] xData;
	String vKW, vxPath, vTestData;
	@Test
	public void myMainTest() throws Exception{
		
		
		
		myFD.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		//Read the TCs and TSs
		xTC = readXL("D:/A16/Excel/KDF Automation.xls", "Test Cases");
		xTS = readXL("D:/A16/Excel/KDF Automation.xls", "Test Steps");
		//Go to each row in the test case and identify which one to execute
		for(int i=1; i<xTC.length; i++){
			System.out.println("TCID is " + xTC[i][0]);
			System.out.println("Exeute column contains " + xTC[i][3]);
			if(xTC[i][3].equalsIgnoreCase("Y")){
				System.out.println("This test case should be executed");
					for (int k=1; k<xTS.length; k++){
						if (xTC[i][0].equalsIgnoreCase(xTS[k][1])){
							System.out.println("Keyword to execute now: " + xTS[k][4]);
							System.out.println("xPath is : " + xTS[k][5]);
							System.out.println("Test Data is : " + xTS[k][6]);
						
							vKW = xTS[k][4];
							vxPath = xTS[k][5];
							vTestData = xTS[k][6];
							
							if(vKW.equalsIgnoreCase("enterText")){
								enterText(myFD, vxPath, vTestData);
							}
							if(vKW.equalsIgnoreCase("navigateBrowser")){
								navigateBrowser(myFD, vTestData);
							}
							if(vKW.equalsIgnoreCase("clickElementbyid")){
								clickElementbyid(myFD, vxPath);
							}
							if(vKW.equalsIgnoreCase("clickElement")){
								clickElement(myFD, vxPath);
							}
							if(vKW.equalsIgnoreCase("selectList")){
								selectList(myFD, vxPath, vTestData);
							}
							if(vKW.equalsIgnoreCase("checkCheckbox")){
								checkCheckbox(myFD, vxPath);
							}
							if(vKW.equalsIgnoreCase("uncheckCheckbox")){
								uncheckCheckbox(myFD, vxPath);
							}
							if(vKW.equalsIgnoreCase("readText")){
								System.out.println("Test Step is: " + readText(myFD, vxPath));
							}
							if(vKW.equalsIgnoreCase("verifyText")){
								System.out.println("Test Step is: " + verifyText(myFD, vxPath, vTestData));
							}
							
							//Capture o/p results
						}
					}
				
				
				} else {
					System.out.println("This test case is ignored");
				}
		}
		
		myFD.quit();
	}
	
	
	
	
	public void navigateBrowser(WebDriver driver, String data){
	driver.navigate().to(data);
	}

	public void enterText(WebDriver driver, String xPath, String data){
		driver.findElement(By.xpath(xPath)).clear();
		driver.findElement(By.xpath(xPath)).sendKeys(data);
		}
	
	public String readText(WebDriver driver, String xPath){
		return driver.findElement(By.xpath(xPath)).getText();
		}
	
	public String verifyText(WebDriver driver, String xPath, String data){
		if (data.equalsIgnoreCase(driver.findElement(By.xpath(xPath)).getText())){
			return "Pass";
		}else {
			return "Fail";
			  }
		}
	
	public void clickElementbyid(WebDriver driver, String xPath){
		driver.findElement(By.id(xPath)).click();
		}
	public void clickElement(WebDriver driver, String xPath){
		driver.findElement(By.xpath(xPath)).click();
		}
	public void selectList(WebDriver driver, String xPath, String data){
		Select myDD = new Select(driver.findElement(By.xpath(xPath)));
	    myDD.selectByVisibleText(data);
	    //driver.findElement(By.cssSelector("option[title=\"5 rooms\"]")).click();
	    myDD = null;
		}

	public void checkCheckbox(WebDriver driver, String xPath){
		if(driver.findElement(By.xpath(xPath)).isSelected()){
			//Do Nothing
		} else {
			driver.findElement(By.xpath(xPath)).click();
			}
		}

	public void uncheckCheckbox(WebDriver driver, String xPath){
		if(!(driver.findElement(By.xpath(xPath)).isSelected())){
			//Do Nothing
		} else {
			driver.findElement(By.xpath(xPath)).click();
			}
		}
	public String[][] readXL(String sPath, String sheet) throws Exception{
	//public void xlRead(String sPath) throws Exception{
	/* int xRows, xCols;
		String[][] xData;	*/
		File myxl = new File(sPath);
		FileInputStream myStream = new FileInputStream(myxl);
		HSSFWorkbook myWB = new HSSFWorkbook(myStream);
		//HSSFSheet mySheet = myWB.getSheetAt(0);	// Referring to 1st sheet
		HSSFSheet mySheet = myWB.getSheet(sheet);
		xRows = mySheet.getLastRowNum()+1;
		xCols = mySheet.getRow(0).getLastCellNum();
		System.out.println("Rows are " + xRows);
		System.out.println("Cols are " + xCols);
		xData = new String[xRows][xCols];
        for (int i = 0; i < xRows; i++) {
	           HSSFRow row = mySheet.getRow(i);
	            for (int j = 0; j < xCols; j++) {
	               HSSFCell cell = row.getCell(j); // To read value from each col in each row
	               String value = cellToString(cell);
	               xData[i][j] = value;
	               }
	        }	
		return xData;
	}
	
	public static String cellToString(HSSFCell cell) {
	// This function will convert an object of type excel cell to a string value
        int type = cell.getCellType();
        Object result;
        switch (type) {
            case HSSFCell.CELL_TYPE_NUMERIC: //0
                result = cell.getNumericCellValue();
                break;
            case HSSFCell.CELL_TYPE_STRING: //1
                result = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_FORMULA: //2
                throw new RuntimeException("We can't evaluate formulas in Java");
            case HSSFCell.CELL_TYPE_BLANK: //3
                result = "-";
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN: //4
                result = cell.getBooleanCellValue();
                break;
            case HSSFCell.CELL_TYPE_ERROR: //5
                throw new RuntimeException ("This cell has an error");
            default:
                throw new RuntimeException("We don't support this cell type: " + type);
        }
        return result.toString();
    }
	public void writeXL(String xlPath, String[][] xldata) throws Exception {
		System.out.println("Inside XL Write");
    	File outFile = new File(xlPath);
        HSSFWorkbook wb = new HSSFWorkbook();
           // Make a worksheet in the XL document created
        /*HSSFSheet osheet = wb.setSheetName(1,"TEST");*/
        HSSFSheet osheet = wb.createSheet("TESTRESULTS");
        // Create row at index zero ( Top Row)
    	for (int myrow = 0; myrow < xRows; myrow++) {
    		//System.out.println("Inside XL Write");
	        HSSFRow row = osheet.createRow(myrow);
	        // Create a cell at index zero ( Top Left)
	        for (int mycol = 0; mycol < xCols; mycol++) {
	        	HSSFCell cell = row.createCell(mycol);
	        	// Lets make the cell a string type
	        	cell.setCellType(HSSFCell.CELL_TYPE_STRING);
	        	// Type some content
	        	cell.setCellValue(xldata[myrow][mycol]);
	        }
	        // The Output file is where the xls will be created
	        FileOutputStream fOut = new FileOutputStream(outFile);
	        // Write the XL sheet
	        wb.write(fOut);
	        fOut.flush();
	        fOut.close();
    	}
    }
}